<template>
  <div class="track_the_playback">
    <el-row
    v-loading.fullscreen.lock="fullscreenLoading">
</el-row>
    <!-- <div class="around"> -->
    <!-- 所有车辆实际作业路线 -->
    <!-- <i
        class="el-icon-kaishi buttonI"
        title="实际作业路线图"
        @click="drawPictureRealityLineAll"
        >实际作业路线图</i
      > -->
    <!-- 所有车辆计划作业路线 -->
    <!-- <i
        class="el-icon-kaishi buttonI"
        title="计划作业路线图"
        @click="drawPicturePlanedLineAll"
        >计划作业路线图</i
      > -->
    <!-- 选择车辆 -->
    <!-- <i class="el-icon-speed" title="车辆名称">车辆名称</i>
      <el-select
        v-model="selectCarVID"
        placeholder="请选择车辆"
        ref="workcarname"
        @change="changVID"
        filterable
        clearable
      >
        <el-option
          v-for="(item, index) in dataCarListPlaned"
          :label="item.LICENSE_PLATE"
          :value="item.VID"
          :key="index"
        ></el-option>
      </el-select> -->
    <!-- 数据列表 -->
    <!-- <i
        class="el-icon-kaishi buttonI"
        title="途径垃圾点位详情"
        @click="openRubbishPointsList"
        >途径垃圾点位详情</i
      > -->
    <!-- </div> -->
    <!-- 地图 -->
    <div class="container" style="padding: 0px">
      <div id="map"></div>
    </div>
    <!-- 弹出框 垃圾点位详情列表 -->
    <el-dialog
      title="途径垃圾点位详情"
      :visible.sync="rubbishPointDetailDialogShow"
      width="50%"
    >
      <el-table :data="dataRubbishPointsPlaned">
        <el-table-column
          prop="PointName"
          label="点位名称"
          align="center"
        ></el-table-column>
        <el-table-column
          :formatter="formatterYJTime"
          label="预计到达时间"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="Wtime"
          label="预计停留时间"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="STARTTIME"
          label="实际到达时间"
          align="center"
        ></el-table-column>
        <el-table-column
          :formatter="formatterRealTime"
          label="实际作业时长（秒）"
          align="center"
        ></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rubbishPointDetailDialogShow = false"
          >取 消</el-button
        >
        <!-- <el-button type="primary" @click="rubbishPointDetailDialogShow = false">确 定</el-button> -->
      </span>
    </el-dialog>
  </div>
</template>

<script>
import MapStr from '@/main.js'
// import tool from '@/Tool.js'
import { newMap } from '@/common/js/map.js'
import imgMarkerCLC from '@/assets/marker/markerImageCLC.png'
import imgMarkerRubbishPoint from '@/assets/marker/rubbishMarker1.png'
import startPlan from '@/assets/marker/STplan.png'
import startReal from '@/assets/marker/STreal.png'
import endPlan from '@/assets/marker/ENDplan.png'
import endReal from '@/assets/marker/ENDreal.png'
// import { filter } from 'vue/types/umd'
import { formatDate } from '@/common/js/date.js'
export default {
  data () {
    return {
      fullscreenLoading: true,
      map: null,
      mapCursor: null,
      mapZoom: 20,
      selectDate: formatDate(new Date(new Date() - 3600 * 1000 * 24), 'yyyy-MM-dd'),
      selectCarVID: '',

      rubbishPointDetailDialogShow: false,

      dataRubbishPointsPlaned: [],
      dataRubbishPointsReal: [],

      dataCarListReality: [],
      dataCarListPlaned: [],

      dataLineReality: [],
      dataLinePlaned: [],
      isEnd: 0,
      clcList: [],
      MapV: {
        mapVPlan: null,
        mapVReal: null,
        mapVPointIcon: null,
        mapVPointText: null,
      },
      markerStartPlan: null,
      markerStartReal: null,
      markerEndPlan: null,
      markerEndReal: null,
    }
  },
  mounted () {
    // const loading = this.$loading({
    //   lock: true,
    //   text: '数据加载中...',
    //   spinner: 'el-icon-loading',
    //   background: 'rgba(0, 0, 0, 0.7)'
    // });
    // setTimeout(() => {
    //   loading.close();
    // }, 18000);
    // 显示地图  
    this.mapShow()
    this.getClcList()
    this.getCarListReality()
    // this.getCarListPlaned()
  },
  methods: {
    formatterYJTime (row) {
      return row.Stime + ' - ' + row.Etime
    },
    formatterRealTime (row) {
      if (row.WtimeR) {
        return row.WtimeR
      } else {
        return '未收运'
      }
    },
    // 获取已规划车辆列表
    async getCarListPlaned () {
      this.dataLinePlaned = []
      var url = 'DataListCompany/GetVehicleRubbishPlan'
      const { data } = await this.$Http.get(url)
      this.dataCarListPlaned = data
      data.forEach(element => {
        this.getLinePlaned(element.VID, element.LICENSE_PLATE);
      });
    },
    // 获取实际作业车辆列表
    async getCarListReality () {
      var url = 'RubbishVehicle/GetRubbishHistoryVehicleCCApi?TYPE=0&WORKDATE=' + this.selectDate + '&CLIENT_NO=' + localStorage.getItem('CLIENT_NO')
      const { data } = await this.$Http.get(url)
      var arrCarNames = []
      this.dataCarListReality = []
      this.dataLineReality = []
      for (var i = 0; i < data.length; i++) {
        var element = data[i];
        if (!arrCarNames.includes(element.车辆编号)) {
          arrCarNames.push(element.车辆编号)
          this.dataCarListReality.push(element)
          // this.getLineReality(element.车辆编号, element.车辆名称);
        }
      };
      for (var i = 0; i < this.dataCarListReality.length; i++) {
        var element = this.dataCarListReality[i];
        var isEnd = (i == (this.dataCarListReality.length - 1))
        this.getLineReality(element.车辆编号, element.车辆名称, isEnd);
      };
    },
    // 获取已规划作业路线，根据已规划作业车辆信息
    async getLinePlaned (VID, NAME) {
      // var url = 'DataListCompany/GetVehicleRubbishPlan'
      var url = 'DataListCompany/GetVehicleRubbishPlanLine?workdate=' + this.selectDate + '&vid=' + VID;
      const { data } = await this.$Http.get(url)
      this.dataLinePlaned.push({ 'key': VID, 'label': NAME, 'data': data[0] })
    },
    // 获取实际作业路线，根据实际作业车辆信息
    async getLineReality (VID, NAME, isEnd) {
      const params = {
        VID: VID,
        startTime: this.selectDate + ' 00:00:00',
        endTime: this.selectDate + ' 23:59:59'
      }
      const { data } = await this.$Http.get('DataListCompany/GetVehicleHistoryInfoListApi', { params })
      if (data.length != 0) {
        this.dataLineReality.push({ 'key': VID, 'label': NAME, 'data': data })
      } else {
        this.$message.error('未获取到轨迹');
      }

      if (isEnd) {
        // console.log(isEnd);
        this.fullscreenLoading = false;
        this.drawPictureRealityLineAll()
      }
    },
    drawPicturePlanedLineAll () {
      var boundPoints = [];
      this.dataLinePlaned.forEach(element => {
        if (element.data.planLines.length == 0) {
          return;
        }
        var pointArr = []
        element.data.planLines.forEach(item => {
          item.Polyline.forEach(v => {
            pointArr.push([v.LONGITUDE, v.LATITUDE])
            boundPoints.push(new BMap.Point(v.LONGITUDE, v.LATITUDE))
          });
        });
        var rgbStr = this.rgb()
        new mapv.baiduMapLayer(this.map, new mapv.DataSet({
          geometry: {
            type: 'LineString',
            coordinates: pointArr
          },
        }), {
          zIndex: -1,
          strokeStyle: rgbStr,//'rgba(255,0,0,0.6)',//47,79,79
          shadowColor: '#00BFFF', // 描边颜色
          shadowBlur: 3,
          lineWidth: 4,
          lineJoin: 'round',
          draw: 'simple'
        });
        // new mapv.baiduMapLayer(this.map, new mapv.DataSet({
        //         geometry: {
        //             type: 'Point',
        //             coordinates: [element.data[0].LONGITUDE, element.data[0].LATITUDE]
        //         },
        //         text: element.label
        //     }), {
        //   draw: 'text',
        //   size: 14,
        //   avoid: true, // 开启文本标注避让
        //   fillStyle: rgbStr,
        //   shadowColor: '#00BFFF', // 描边颜色
        //   shadowBlur: 3,
        //   textBaseline: 'middle',
        // })
      });
      this.map.setViewport(boundPoints);
    },
    drawPictureRealityLineAll () {
      var boundPoints = [];
      this.dataLineReality.forEach(element => {
        var pointArr = []
        element.data.forEach(item => {
          // var item = this.dataRealRoute[i];
          pointArr.push([item.Lng, item.Lat])
          boundPoints.push(new BMap.Point(item.Lng, item.Lat))
        });
        var rgbStr = this.rgb()
        new mapv.baiduMapLayer(this.map, new mapv.DataSet({
          geometry: {
            type: 'LineString',
            coordinates: pointArr
          },
        }), {
          zIndex: -1,
          strokeStyle: rgbStr,//'rgba(255,0,0,0.6)',//47,79,79
          shadowColor: '#000000', // 描边颜色
          shadowBlur: 3,
          lineWidth: 4,
          lineJoin: 'round',
          draw: 'simple'
        });
        new mapv.baiduMapLayer(this.map, new mapv.DataSet({
          geometry: {
            type: 'Point',
            coordinates: [element.data[0].Lng, element.data[0].Lat]
          },
          text: element.label
        }), {
          draw: 'text',
          size: 14,
          avoid: true, // 开启文本标注避让
          fillStyle: rgbStr,
          shadowColor: '#000000', // 描边颜色
          shadowBlur: 3,
          textBaseline: 'middle',
        })
      });
      this.map.setViewport(boundPoints);
    },
    rgb () {//rgb颜色随机
      var r = Math.floor(Math.random() * 256);
      var g = Math.floor(Math.random() * 256);
      var b = Math.floor(Math.random() * 256);
      var rgb = 'rgb(' + r + ',' + g + ',' + b + ')';
      return rgb;
    },
    // 画途经垃圾点位
    drawRubbishPoints () {
      const _self = this;

      let img = new Image();
      img.src = imgMarkerRubbishPoint
      img.onload = function () {
        //循环加载同一张图片的车辆数据
        let arrayImage = _self.dataRubbishPointsReal.map(v => {
          v.geometry = {
            type: 'Point',
            coordinates: [v.LONGITUDE, v.LATITUDE]
          }
          v.icon = img;
          v.text = v.Number + ' ' + v.PointName
          return v;
        })
        if (_self.MapV.dataSetPoint) {
          _self.MapV.dataSetPoint.set(arrayImage);
        } else {
          _self.MapV.dataSetPoint = new mapv.DataSet(arrayImage);
          let optionsICON = {
            draw: 'icon',
            width: 28, // 规定图像的宽度
            height: 32, // 规定图像的高度
            offset: { // 偏移值
              x: 0,
              y: 25
            }
          }

          let optionsTEXT = {
            draw: 'text',
            size: 14,
            avoid: true, // 开启文本标注避让
            textBaseline: 'middle',
            offset: { // 文本便宜值
              x: 0,
              y: 50
            }
          }
          new mapv.baiduMapLayer(_self.map, _self.MapV.dataSetPoint, optionsICON)
          new mapv.baiduMapLayer(_self.map, _self.MapV.dataSetPoint, optionsTEXT)
        }
      }
    },
    // 获取处理厂列表
    async getClcList () {
      const { data } = await this.$Http.get('/RubbishVehicle/getPlaceCLC?ClientNo=' + localStorage.getItem('CLIENT_NO'))
      this.clcList = data
      this.drawCLCPoints()
    },
    // 画处理厂点位
    drawCLCPoints () {
      const _self = this;

      let img = new Image();
      img.src = imgMarkerCLC
      img.onload = function () {
        //循环加载同一张图片的车辆数据
        let arrayImage = _self.clcList.map(v => {
          v.geometry = {
            type: 'Point',
            coordinates: [v.LONGITUDE, v.LATITUDE]
          }
          v.icon = img;
          v.text = v.NAME
          return v;
        })
        // if (_self.MapV.dataSetPoint) {
        //   _self.MapV.dataSetPoint.set(arrayImage);
        // } else {
        var dataSetCLC = new mapv.DataSet(arrayImage);
        let optionsICON = {
          draw: 'icon',
          width: 40, // 规定图像的宽度
          height: 40, // 规定图像的高度
          offset: { // 偏移值
            x: 0,
            y: 15
          }
        }

        let optionsTEXT = {
          draw: 'text',
          size: 14,
          avoid: true, // 开启文本标注避让
          textBaseline: 'middle',
          offset: { // 文本便宜值
            x: 0,
            y: 50
          }
        }
        new mapv.baiduMapLayer(_self.map, dataSetCLC, optionsICON)
        new mapv.baiduMapLayer(_self.map, dataSetCLC, optionsTEXT)
        // }
      }
    },
    setDistance () {
      if (!this.mapCursor) {
        this.mapCursor = new BMapLib.DistanceTool(this.map);
      }
      if (this.mapCursor.isOpen) {
        //结束测量
        this.mapCursor.close();
      } else {
        //开始测量
        this.mapCursor.open()
      }
    },
    // 显示地图
    mapShow () {
      // 百度地图API功能
      this.map = newMap();
      this.map.centerAndZoom(new BMap.Point(MapStr.DefaultPointX, MapStr.DefaultPointY), this.mapZoom)// 初始化地图,设置中心点坐标和地图级别

      // var cr = new BMap.CopyrightControl({
      //   anchor: BMAP_ANCHOR_TOP_RIGHT,
      //   offset: new BMap.Size(20, 20)
      // });   //设置版权控件位置
      // this.map.addControl(cr); //添加版权控件
      // cr.addCopyright({
      //   id: 1,
      //   content: "<div id='resultMap' >测量结果<p>这是一个段落。</p></div>"
      //   // content: "<img src='../img/baidu.jpg' width='50px' height='50px'/><a href='#' style='font-size:16px;color:#000'>@我是自定义版权控件呀</a>", 
      // });
    }
  }
}
</script>

<style scoped lang="less">
.track_the_playback {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .around {
    padding: 10px 100px;
    height: 40px;
    background-color: #007acc;
    &:first-child {
      padding-left: 10px;
      height: 30px;
      // line-height: 30px;
      i {
        color: #fff;
        font-size: 18px;
        font-weight: bold;
        //width: 30px;
        height: 30px;
        line-height: 28px;
        text-align: center;
        vertical-align: middle;
        cursor: pointer;
        margin-right: 15px;
      }
      // .el-icon-s-operation {
      //   font-size: 22px;
      // }
    }
  }
  .container {
    flex: 1;
    #map {
      height: 100%;
      width: 100%;
    }
  }
}
.buttonI {
  border: 1px solid #fff;
  padding: 0px 8px;
  border-radius: 6px;
  margin-left: 15px;
}
</style>
